import React from 'react'
import Pinyin from "../../../utils/pinyin";
import ClickableBtn from "../../../shared-components/ClickableBtn/ClickableBtn";
import EventBtn from "../EventBtn/EventBtn";


const BtnSortedByPinyin = props => {
    const {btns,} = props
    let keyName = 'short_name_zh'
    if (props.keyName) {
        keyName = props.keyName
    }

    const sortedBtn = [...btns]
        .map(btn => {
            const btnPy = new Pinyin(btn.value[keyName])
            btn.pinyin = btnPy.getFullChars()
            return btn
        })
        .sort((a, b) => {
            if (a.pinyin[0] < b.pinyin[0]) {
                return -1
            } else if (a.pinyin[0] === b.pinyin[0]) {
                return 1
            } else {
                return 0
            }
        })


    let sortedByPinyin = {}

    sortedBtn.map(btn => {
        let first = btn.pinyin[0]
        if (sortedByPinyin[first]) {
            sortedByPinyin[first].push(btn)
        } else {
            sortedByPinyin[first] = [btn]
        }
    })

    const btnListGen = btns => {
        const t = btns.map((event, index) => {
            const id = event.id
            const value = event.value
            const active = event.active
            // let pinyin = new Pinyin(value.short_name_zh)
            // console.log(pinyin.getFullChars())

            return event ? <EventBtn
                    key={index}
                    active={`${active}`}
                    onClick={(e) => props.selectOneGame(e, event)}
                >
                    {/*{item.title}*/}
                    {value[keyName]}
                </EventBtn>
                : null
        })

        return <div className='flex flex-wrap-container'>
            {t}
        </div>

    }

    const letters = Object.keys(sortedByPinyin)
    const template = letters ? letters.map((letter, index) => {
        if (letter === "undefined") {
            return null
        } else {
            return <div key={index} style={{padding: '15px'}}>
                <p style={{
                    fontSize: '16px',
                    color: 'rgba(51,51,51,1)',
                    marginBottom: '8px',
                }}>{letter}</p>
                {btnListGen(sortedByPinyin[letter])}
            </div>
        }

    })
    : null

    return  <>
        <div style={{marginBottom: '72px'}}>
            {template}
        </div>
    </>
}

export default BtnSortedByPinyin
